/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.planning;

import cn.ac.nercis.pes.common.constant.knowledge.TargetType;
import cn.ac.nercis.pes.community.constant.AppConstants;
import cn.ac.nercis.pes.community.constant.SaveMethod;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.evaluation.planning.layer.ManagementEvalMethodController;
import cn.ac.nercis.pes.community.controller.evaluation.planning.layer.TechnologyEvalMethodController;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.planning.ContentConfirmView;
import cn.ac.nercis.pes.community.views.evaluation.planning.layer.ManagementEvalMethodView;
import cn.ac.nercis.pes.community.views.evaluation.planning.layer.TechnologyEvalMethodView;
import cn.ac.nercis.pes.model.dto.knowledge.KmSimpleTargetDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationRangeService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 资产对象测评方式管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class EvaluationMethodController implements Initializable, GlobalEventHandle {

    @FXML
    private StackPane page;
    @FXML
    private BorderPane bodyPane;
    @FXML
    private Button relatedButton;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;
    @FXML
    private Label currentAssetLbl;

    @FXML
    private AnchorPane emptyPane;
    @FXML
    private ImageView emptyImageView;
    @FXML
    private Label emptyLabel;

    private MenuVO currentAssetNode;
    private String currentSystemId;
    private KmSimpleTargetDTO currentLayerTarget;

    private final EvaluationRangeService evaluationRangeService;

    public EvaluationMethodController() {
        this.evaluationRangeService = SpringUtils.getBean(EvaluationRangeService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        relatedButton.setGraphic(IconUtils.getGlyph("related-button-icon","btn-icon"));
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));

        ControlUtils.initEmptyImageView(this.emptyImageView,log);
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
    }

    public void initializeData(String systemId,MenuVO assetNode){
        LogUtils.info(log, "初始化资产对象测评方式信息...");
        this.currentSystemId = systemId;
        this.currentAssetNode = assetNode;
        ControlUtils.setLabelTextByLimit(this.currentAssetLbl, currentAssetNode.getTitle(),
                AppConstants.MAX_SHOW_TEXT_LENGTH);
        this.loadLayerTargetData();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        onTmpSave();
    }

    @FXML
    public void onRelatedClick() {
        LogUtils.info(log, "执行关联指标操作...");
        var view = AppStore.getEvaluationView(this.currentSystemId, ContentConfirmView.class);
        if(view.getController() instanceof ContentConfirmController controller){
            controller.gotoRelatedTarget(currentAssetNode);
        }
    }

    @FXML
    public void onTmpSave() {
        LogUtils.info(log, "执行暂存操作...");
        if(Objects.isNull(this.currentLayerTarget)){
            return;
        }
        senderSaveEvent(false);
    }

    @FXML
    public void onFinishSave() {
        LogUtils.info(log, "执行保存操作...");
        if(Objects.isNull(this.currentLayerTarget)){
            return;
        }
        senderSaveEvent(true);
    }

    private void loadLayerTargetData() {
        LogUtils.info(log, "获取系统资产关联的层面指标信息...");
        LogUtils.record(log, "请求数据，systemId：{},data:{}", this.currentSystemId, this.currentAssetNode.getId());
        CompletableFuture.supplyAsync(() -> this.evaluationRangeService.findLayerTargetByAsset(this.currentSystemId,
                        this.currentAssetNode.getCode()))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        this.loadEvalMethodContent(res.getData());
                    } else {
                        //跳转到关联指标页面
                        onRelatedClick();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("获取系统资产关联的层面指标信息出错!", ex);
                    return null;
                });
    }

    private void loadEvalMethodContent(List<KmSimpleTargetDTO> layerTargets){
        this.currentLayerTarget=  layerTargets.stream().findFirst().orElse(null);
        if(Objects.isNull(currentLayerTarget)){
            return;
        }
        if(currentLayerTarget.getType() == TargetType.TECHNOLOGY){
            var view = AppStore.getEvaluationView(this.currentSystemId, TechnologyEvalMethodView.class);
            bodyPane.setCenter(Objects.requireNonNull(view).load());
            if (view.getController() instanceof TechnologyEvalMethodController controller) {
                controller.initializeData(this.currentSystemId, currentAssetNode, currentLayerTarget);
            }
        }else{
            var view = AppStore.getEvaluationView(this.currentSystemId, ManagementEvalMethodView.class);
            bodyPane.setCenter(Objects.requireNonNull(view).load());
            if (view.getController() instanceof ManagementEvalMethodController controller) {
                controller.initializeData(this.currentSystemId, currentAssetNode, currentLayerTarget);
            }
        }
    }

    private void senderSaveEvent(boolean finish) {
        if(currentLayerTarget.getType() == TargetType.TECHNOLOGY){
            var view = AppStore.getEvaluationView(this.currentSystemId, TechnologyEvalMethodView.class);
            if (view.getController() instanceof TechnologyEvalMethodController controller) {
                controller.saveEvaluationMethod(SaveMethod.SAVE, finish);
            }
        }else{
            var view = AppStore.getEvaluationView(this.currentSystemId, ManagementEvalMethodView.class);
            if (view.getController() instanceof ManagementEvalMethodController controller) {
                controller.saveEvaluationMethod(SaveMethod.SAVE, finish);
            }
        }
    }
}